# ! /usr/bin/env python3.7
"""
app 初始化
"""
import logging

import hashids
from fastapi import FastAPI
from settings import Config
from starlette.middleware.trustedhost import TrustedHostMiddleware
from strawberry.fastapi import GraphQLRouter
from tortoise.contrib.fastapi import register_tortoise

logger = logging.getLogger(__name__)
my_hash = hashids.Hashids(salt=Config.hash_id_salt, min_length=10)


def init_middleware(app: FastAPI):
    app.add_middleware(TrustedHostMiddleware, allowed_hosts=["*"])


def init_mysql(app):
    register_tortoise(
        app,
        db_url=Config.MYSQL_URL,
        modules={"models": ["app.models"]},
        generate_schemas=True,
        add_exception_handlers=True,
    )

    # todo 后续会直接在mysql_init中导入sql
    async def init_permission():
        from app.models import Permission
        from app.models.permissions import PermissionEnum

        await Permission.ensure_many({_enum for _enum in PermissionEnum})

    app.router.on_startup.append(init_permission)


def init_views(_app: FastAPI) -> FastAPI:
    from app.api.graphql import schema

    graphql_app = GraphQLRouter(schema=schema)

    _app.include_router(graphql_app, prefix="/api/graphql")
    return _app


def create_app():
    app = FastAPI(debug=True)
    init_middleware(app)
    init_mysql(app)

    init_views(app)
    return app
